package org.freedoit.server;

import java.util.Date;

import org.freedoit.client.LoginService;
import org.freedoit.server.dao.DAOFactory;
import org.freedoit.server.dao.UserDAO;
import org.freedoit.server.om.User;
import org.freedoit.shared.exception.LogicException;
import org.freedoit.shared.exception.ServerException;
import org.freedoit.shared.util.Constants;
import org.freedoit.shared.util.Utils;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	public String register(String username, String password) throws ServerException, LogicException {
		// TODO Auto-generated method stub
		String key = getKey(username, password);
		
		if (key == null) {
			throw new ServerException("Failed to save password");
		} else {
			UserDAO userDAO = DAOFactory.getUserDAO();
			
			User user = userDAO.findByUserName(username);
			if (user == null) {
				userDAO.persist(new User(username, key, new Date(), Constants.ACTIVE_INTEGER));
				return "Registered!!";
			} else {
				throw new LogicException("User already existed");
			}
		}
	}
	
	private String getKey(String username, String password) {
		return Utils.getMD5(password);
	}

	public String login(String username, String password) throws ServerException, LogicException {
		// TODO Auto-generated method stub
		String key = getKey(username, password);
		
		if (key == null) {
			throw new ServerException("Failed to login");
		} else {
			UserDAO userDAO = DAOFactory.getUserDAO();
			
			User user = userDAO.findByUserName(username);
			if (user == null) {
				throw new LogicException("User Not exists or wrong password");
			} else {
				if (key.endsWith(user.getUserKey())) {
					this.getThreadLocalRequest().getSession().setAttribute(Constants.DOIT_USER_KEY, user);
					return "Login Successfully";
				} else {
					throw new LogicException("User Not exists or wrong password");
				}
			}
		}
	}

}
